package com.moana.buyTicket.dao;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import javax.jdo.JDOHelper;
import javax.jdo.PersistenceManager;
import javax.jdo.PersistenceManagerFactory;
import javax.jdo.Query;
import javax.jdo.Transaction;

import com.moana.buyTicket.entity.Ticket;
import com.moana.buyTicket.entity.TranFlow;
import com.moana.buyTicket.util.DBOperator;

public class TicketDao {
	PersistenceManagerFactory pmf;
	

	public TicketDao(){
		pmf = JDOHelper.getPersistenceManagerFactory("buyTicket");
	}
	
	public TicketDao(PersistenceManagerFactory pmf){
		this.pmf = pmf;
	}
	
	protected PersistenceManager getPersistenceManager(){
		return pmf.getPersistenceManager();
	}
	
	private static String querySQL = "select * from M_TICKET";
	
	//读取电影票
	public List<Ticket> readTickets() {
		PersistenceManager pm = pmf.getPersistenceManager();
		Transaction tx = pm.currentTransaction();
		List<Ticket> tickets = null ;
		try{
			tx.begin();
			Ticket ticket = new Ticket();
			ticket.setStatus(0);
			Query query = pm.newQuery("javax.jdo.query.SQL",querySQL);
			query.setResultClass(Ticket.class);
			tickets = ((List<Ticket>)query.execute()); 
	/*		Collection queryResult = (Collection) query.execute();
			List<Ticket> detachCopyAll = (List<Ticket>) pm.detachCopyAll(queryResult);
			tickets = detachCopyAll;*/
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			//	pm.close();
			//	pmf.close();
		}
		return tickets;
	}
	
	//更新电影票
	public String updateTickets(List<Ticket> tickets,List<TranFlow> tranFlows){
		PersistenceManager pm = pmf.getPersistenceManager();
		Transaction tx = pm.currentTransaction();
		try{
			tx.begin();
			//交易流水表插入
			for(TranFlow tranFlow:tranFlows){
				pm.makePersistent(tranFlow);
			}		
			//******电影票状态更新******
			tx.commit();
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			if(tx.isActive()){
				tx.rollback();
			}
			pm.close();
			pmf.close();
		}
		
		return "0";
	}

}
